package com.mapguru;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;


public class MapMeActivity extends MapActivity {
	MapView mapView;
	MapController mc;
	GeoPoint gp;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_me);
        mapView = (MapView)findViewById(R.id.mapMe);
        
		/*gp = new GeoPoint(
	            (int) (1.352566007d * 1E6), 
	            (int) (103.78921587d * 1E6));
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> overlayList = mapView.getOverlays();
        overlayList.clear();
        overlayList.add(mapOverlay);*/
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);
        mapView.invalidate();      


        

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater menuInflater = getMenuInflater();
    	menuInflater.inflate(R.menu.map_menu, menu);
		return true;    	
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem){
    	return true;
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.map_menu, menu);
    }
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	public void toggleMapView(View view){
		
		if(mapView.isSatellite()) {
			mapView.setSatellite(false);			
		} else {
			mapView.setSatellite(true);
		}
	}
	public void tagIt(View view){
		mc = mapView.getController();
		gp = new GeoPoint(
		            (int) (1.352566007d * 1E6), 
		            (int) (103.78921587d * 1E6));
		mc.animateTo(gp);
		mc.setZoom(17);
		mapView.invalidate();
		
	}
	public void drawRoute(View view) {
        double src_lat = 25.04202; // the testing source
        double src_long = 121.534761;
        double dest_lat = 25.05202; // the testing destination
        double dest_long = 121.554761;
        GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
        (int) (src_long * 1E6));
        GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
        (int) (dest_long * 1E6));

        DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, mapView);
	}
	
	class MapOverlay extends Overlay{
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
			super.draw(canvas, mapView, shadow, when);
			Point screenPts = new Point();
			mapView.getProjection().toPixels(gp, screenPts);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.green_pin);
			canvas.drawBitmap(bmp, screenPts.x, screenPts.y-47,null);			
			return true;
			
		}
		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			super.onTouchEvent(event, mapView);
			if (event.getAction()==1) {
				
				// Touch to Display the latitude and longitude
				GeoPoint p = mapView.getProjection().fromPixels((int)event.getX(),(int)event.getY());				
//				Toast.makeText(getApplication(),p.getLatitudeE6()/1E6 + "," + p.getLongitudeE6()/1E6,Toast.LENGTH_SHORT).show();
				
				// Get the place names
		//		Geocoder gc = new Geocoder(getApplicationContext(),Locale.getDefault());
				
/*				try {
					List<Address> address = gc.getFromLocation(p.getLatitudeE6()/1E6, p.getLongitudeE6()/1E6, 1);
					String add="";
					for (int i=0; i<address.get(0).getMaxAddressLineIndex();i++) {
						add = add + address.get(0).getAddressLine(i) + "\n";
					}
				//		Toast.makeText(getApplication(), add, Toast.LENGTH_SHORT).show();
				}
				catch(IOException e){
					e.printStackTrace();
				}*/
				
						}
			return true;
		}
	}
	// External class one starts here
	private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
	{
	// connect to map web service
	StringBuilder urlString = new StringBuilder();
	urlString.append("http://maps.google.com/maps?f=d&hl=en");
	urlString.append("&saddr=");//from
	urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
	urlString.append(",");
	urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
	urlString.append("&daddr=");//to
	urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
	urlString.append(",");
	urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
	urlString.append("&ie=UTF8&0&om=0&output=kml");
	Log.d("xxx","URL="+urlString.toString());
	// get the kml (XML) doc. And parse it to get the coordinates(direction route).
	Document doc = null;
	HttpURLConnection urlConnection= null;
	URL url = null;
	try
	{
	url = new URL(urlString.toString());
	urlConnection=(HttpURLConnection)url.openConnection();
	urlConnection.setRequestMethod("GET");
	urlConnection.setDoOutput(true);
	urlConnection.setDoInput(true);
	urlConnection.connect();

	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	doc = db.parse(urlConnection.getInputStream());

	if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
	{
	//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
	String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
	Log.d("xxx","path="+ path);
	String [] pairs = path.split(" ");
	String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
	// src
	GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
	mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
	GeoPoint gp1;
	GeoPoint gp2 = startGP;
	for(int i=1;i<pairs.length;i++) // the last one would be crash
	{
	lngLat = pairs[i].split(",");
	gp1 = gp2;
	// watch out! For GeoPoint, first:latitude, second:longitude
	gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
	mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
	Log.d("xxx","pair:" + pairs[i]);
	}
	mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
	}
	}
	catch (MalformedURLException e)
	{
	e.printStackTrace();
	}
	catch (IOException e)
	{
	e.printStackTrace();
	}
	catch (ParserConfigurationException e)
	{
	e.printStackTrace();
	}
	catch (SAXException e)
	{
	e.printStackTrace();
	}
	}

	

}